package tech.realcpf.duckengine1.sqlparser;

import org.apache.calcite.sql.SqlDialect;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.calcite.sql.parser.SqlParser;
import tech.realcpf.duckengine1.biz.BizCatalog;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SqlReLocateFactory {

    private static final SqlDialect PG_DIALECT = SqlDialect.DatabaseProduct.POSTGRESQL.getDialect();

    private static final List<SqlReLocator> sqlReLocators = new LinkedList<>();

    public static String re(String sql) throws SqlParseException {
        SqlParser sqlParser = SqlParser.create(sql);
        SqlNode sqlNode = sqlParser.parseStmt();
        for (SqlReLocator sqlReLocator : sqlReLocators) {
            if (sqlReLocator.support(sqlNode)) {
                sqlReLocator.relocate(sqlNode);
            }
        }
        return sqlNode.toSqlString(PG_DIALECT).getSql();
    }

    public static String reTableName(String sql,Map<String, BizCatalog> catalogMap,String s3UserUrl) throws SqlParseException {
        SqlParser sqlParser = SqlParser.create(sql);
        SqlNode sqlNode = sqlParser.parseStmt();
        TableNameSqlReLocator tableNameSqlReLocator = new TableNameSqlReLocator(catalogMap,s3UserUrl);
        tableNameSqlReLocator.relocate(sqlNode);
        return sqlNode.toSqlString(PG_DIALECT).getSql();
    }
}
